<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class DbPdo
{
    private static $instance;
    private $m_connection;
    private $m_transactionStarted;

    private function __construct( $db )
    {
		$hostname = $db['default']['hostname'];
        $dbname = $db['default']['database'];
        $port = $db['default']['port'];
        $username = $db['default']['username'];
        $password = $db['default']['password'];
		
		$dsn = "pgsql:host=$hostname;dbname=$dbname;port=$port";
		$options = array( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',); 

        $this->m_connection = new PDO( $dsn, $username, $password, $options );
        $this->m_connection->exec("SET CHARACTER SET utf8");
        $this->m_connection->exec("SET NAMES utf8");
        $this->m_connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        $this->m_transactionStarted = false;
    }
    
    public function __destruct()
    {
        if ($this->m_transactionStarted)
            $this->m_connection->rollBack();  
    }
    
    private function __clone()
    {
        
    }
    
    public function prepare( $sqlStatement )
    {
        return $this->m_connection->prepare( $sqlStatement );
    }
	
	public function lastInsertedId()
	{
		return $this->m_connection->lastInsertId();
	}
    
    public function beginTransaction()
    {
        $this->m_connection->beginTransaction();
        $this->m_transactionStarted = true;
    }
    
    public function commit()
    {
        $this->m_connection->commit();
        $this->m_transactionStarted = false;
    }
    
    public function rollBack()
    {
        $this->m_connection->rollBack();
        $this->m_transactionStarted = false;
    }

    public static function getInstance()
    {
        if (! isset(self::$instance))
        {
            $object = __CLASS__;
            include  APPPATH . '/config/database.php';
            self::$instance = new $object( $db );
        }
        return self::$instance;
    }
}

?>
